package org.wishwork.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.wishwork.constant.Constants;
import org.wishwork.exception.ExceptionEnum;
import org.wishwork.exception.JSTException;

/**
 * @description:
 * @author: WangYX
 * @create: 2022-04-02 15:52
 * @Version: 1.0.0
 **/
public abstract class Api<T, V> {

    /**
     * 对外暴露的方法
     *
     * @param v
     * @return
     * @throws Exception
     */
    public T business(V v) throws Exception {
        String result = query(v);
        JSONObject data = handler(result);
        T t = process(data, v);
        return t;
    }


    /**
     * 调用聚水潭的请求处理
     *
     * @param v
     * @return
     * @throws Exception
     */
    protected abstract String query(V v) throws Exception;


    /**
     * 请求完成之后的json数据处理
     *
     * @param result 第三方请求之后返回的json字符串
     * @return
     * @throws Exception
     */
    protected JSONObject handler(String result) throws Exception {
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.getString("code");
        if (Constants.SUCCESS.equals(code)) {
            JSONObject data = jsonObject.getJSONObject("data");
            return data;
        } else {
            String msg = jsonObject.getString("msg");
            throw new JSTException(ExceptionEnum.SERVICE_ERROR_C0001, ExceptionEnum.SERVICE_ERROR_C0001.getMessage() + ":" + msg);
        }
    }

    /**
     * 请求完成之后的业务处理
     *
     * @param data 调用聚水潭返回的json数据
     * @param v    调用聚水潭的请求的对象
     * @return
     * @throws Exception
     */
    protected abstract T process(JSONObject data, V v) throws Exception;

}
